#include "tim.h"
TIM_HandleTypeDef htim1;

/* USER CODE BEGIN PV */
/* Captured Values */
uint32_t uwIC2Value1_T2CH1 = 0;
uint32_t uwIC2Value2_T2CH1 = 0;
uint32_t Diff_high = 0;
uint32_t Diff_low = 0;
/* Capture index */
uint16_t uhCaptureIndex_T2CH1 = 0;

/* Frequency Value */
uint32_t uwFrequency = 0;
uint8_t duty_T3CH2 = 0;
/* USER CODE END PV */


void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
  if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2)
  {
    if(uhCaptureIndex_T2CH1 == 0)
    {
		  /* Get the 1st Input Capture value */
		  uwIC2Value1_T2CH1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_2);
		  uhCaptureIndex_T2CH1 = 1;
    }
    else if(uhCaptureIndex_T2CH1 == 1)
    {
		  /* Get the 2nd Input Capture value */
		  uwIC2Value2_T2CH1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_2); 

		  /* Capture computation */
		  if (uwIC2Value2_T2CH1 > uwIC2Value1_T2CH1)
		  {
			Diff_high = (uwIC2Value2_T2CH1 - uwIC2Value1_T2CH1); 
		  }
		  else if (uwIC2Value2_T2CH1 < uwIC2Value1_T2CH1)
		  {
			/* 0xFFFF is max TIM1_CCRx value */
			Diff_high = ((0xFFFF - uwIC2Value1_T2CH1) + uwIC2Value2_T2CH1) + 1;
		  }
		  else
		  {
			/* If capture values are equal, we have reached the limit of frequency
			   measures */
			Error_Handler();
		  }
		  uwIC2Value1_T2CH1 = uwIC2Value2_T2CH1;
    }
	else
    {
		  /* Get the 2nd Input Capture value */
		  uwIC2Value2_T2CH1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_2); 

		  /* Capture computation */
		  if (uwIC2Value2_T2CH1 > uwIC2Value1_T2CH1)
		  {
			Diff_low = (uwIC2Value2_T2CH1 - uwIC2Value1_T2CH1); 
		  }
		  else if (uwIC2Value2_T2CH1 < uwIC2Value1_T2CH1)
		  {
			/* 0xFFFF is max TIM1_CCRx value */
			Diff_low = ((0xFFFF - uwIC2Value1_T2CH1) + uwIC2Value2_T2CH1) + 1;
		  }
		  else
		  {
			/* If capture values are equal, we have reached the limit of frequency
			   measures */
			Error_Handler();
		  }

		  /* Frequency computation: for this example TIMx (TIM1) is clocked by
			 APB2Clk */      
		  uwFrequency = 1e6 / (Diff_high + Diff_low);
		  duty_T3CH2 = Diff_high * 100.0f / (Diff_high + Diff_low);
		  uhCaptureIndex_T2CH1 = 0;
    }
  }
}